<?php

namespace App\Http\Services;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use Darabonba\OpenApi\Models\Config;

/**
 * Class OperateLogService
 * @package App\Http\Services
 */
class SendSmsService
{
    /**
     * OperateLogService constructor.
     */
    public function __construct()
    {

    }

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function send($mobile, $content, $type = 1, $country_code = "")
    {
        if (!$content || !$mobile) return;
        $templates = [
            1 => [
                'template_id' => 'SMS_471815125',
                'content' => $content,
//                'template_param' => json_encode($content)
            ],
            2 => [
                'template_id' => 'SMS_471815125',
                "content" => [
                    'code' => $content
                ]
            ]
        ];

        if (empty($templates[$type]))
            return;

        $template_id = $templates[$type]['template_id']; //国内短信id
        if ($country_code && $country_code != 86) {
//            $template_id = $template_id;
            $mobile = '00' . $country_code . $mobile;
        }

        $client = self::createClient(env('SMS_KEY_ID'), env('SMS_KEY_SECRET'));
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $mobile,
            "signName" => env("SMS_SIGN_NAME"),
            "templateCode" => $template_id,
            "templateParam" => json_encode($templates[$type]['content'])
        ]);

// 复制代码运行请自行打印 API 的返回值
        $res = $client->sendSms($sendSmsRequest);
        return [
            'code' => $res->body->code,
            'message' => $res->body->code,
        ];

    }

}
